package com.mayikt.servlet;

import com.mayikt.entity.FlightEntity;
import com.mayikt.service.FlightService;
import com.mayikt.utils.MayiktJdbcUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/deleteFlight")
public class DeleteFlightServlet extends HttpServlet {
    private FlightService flightService = new FlightService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        try {

            String idStr = req.getParameter("id");
            // 增强校验逻辑
            if (!StringUtils.isNumeric(idStr)) {
                req.setAttribute("errorMsg", "非法航班ID");
                req.getRequestDispatcher("error.jsp").forward(req, resp);
                return;
            }

            int id = Integer.parseInt(idStr);

            // 前置检查是否存在
            FlightEntity existFlight = flightService.getByIdFlight(id);
            if (existFlight == null) {
                req.setAttribute("errorMsg", "航班不存在或已被删除");
                req.getRequestDispatcher("error.jsp").forward(req, resp);
                return;
            }

            int result = flightService.deleteFlightById(id);

            if (result <= 0) {
                req.setAttribute("errorMsg", "删除航班失败");
                req.getRequestDispatcher("error.jsp").forward(req, resp);
                return;
            }
//            else {
//                req.getRequestDispatcher("showFlight").forward(req,resp);
//            }
            // 删除成功后跳转
            //resp.sendRedirect("show.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("errorMsg", "系统错误：" + e.getMessage());
            req.getRequestDispatcher("error.jsp").forward(req, resp);
        }
    }
}
